package com.five.service.impl;

import com.five.dto.AuthorUpdateRequest;
import com.five.mapper.AuthorMapper;
import com.five.pojo.Author;
import com.five.service.AuthorProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;

@Service
public class AuthorProfileServiceImpl implements AuthorProfileService {

    @Autowired
    private AuthorMapper authorMapper;

    /**
     * 获取作者信息
     * @param authorId
     * @return
     */
    @Override
    public Author getAuthorProfile(Long authorId) {
        // 查询作者信息
        Author author = authorMapper.selectById(authorId);
        if (author == null) {
            return null;
        }

        // 计算注册天数
        if (author.getCreateTime() != null) {
            long days = ChronoUnit.DAYS.between(
                    author.getCreateTime().toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDate(),
                    LocalDate.now()
            );
            author.setRegisterDays(days);
        }

        return author;
    }

    /**
     * 更新作者信息
     * @param request
     */
    @Override
    public void updateAuthorProfile(AuthorUpdateRequest request) {
        // 查询作者信息
        Author author = authorMapper.selectById(request.getId());
        if (author != null) {
            author.setPenName(request.getPenName());
            author.setAvatar(request.getAvatar());
            author.setIntro(request.getIntro());
            author.setUpdateTime(new Date());

            // 更新作者信息
            authorMapper.update(author);
        }
    }
}
